package com.hwd.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.hwd.srb.common.constant.Constants;
import com.hwd.srb.common.exception.Assert;
import com.hwd.srb.common.result.R;
import com.hwd.srb.common.result.ResponseEnum;
import com.hwd.srb.common.util.JwtUtils;
import com.hwd.srb.core.hfb.RequestHelper;
import com.hwd.srb.core.pojo.vo.InvestVo;
import com.hwd.srb.core.service.LendItemService;
import com.hwd.srb.core.service.TransFlowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 前端控制器
 * </p>
 *
 * @author 黄伟东/Victor
 * @since 2022-03-10
 */
@RestController
@RequestMapping("/api/core/lendItem")
@Api(tags = "标的出借接口")
@Slf4j
public class ApiLendItemController {

    @Resource
    private LendItemService lendItemService;

    @Resource
    TransFlowService transFlowService;

    /**
     * 会员投资提交数据，调用hfb接口，生成并返回投资表单
     *
     * @param investVO 投资信息，包含lendId，investAmount
     * @return com.hwd.srb.common.result.R
     */
    @ApiOperation(value = "会员投资提交数据")
    @PostMapping("/auth/commitInvest")
    public R commitInvest(@ApiParam(value = "投资信息", required = true) @RequestBody InvestVo investVO,
                          HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding(Constants.UTF8);
        Long userId = Long.valueOf(request.getHeader(Constants.USER_ID));
        String userName = JwtUtils.getUserName(request.getHeader(Constants.TOKEN));

        investVO.setInvestUserId(userId);
        investVO.setInvestName(userName);
        String formStr = lendItemService.commitInvest(investVO);

        return R.ok().data("formStr", formStr);
    }

    /**
     * 会员投资异步回调
     *
     * @param request 请求对象， 包含结果参数
     * @return java.lang.String
     */
    @ApiOperation("会员投资异步回调")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {

        // 获取结果参数
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());

        // 校验签名
        if (!RequestHelper.isSignEquals(paramMap)) {
            log.info("会员投资异步回调签名错误：" + JSON.toJSONString(paramMap));
            return "fail";
        }

        // 校验投标是否成功
        if (!"0001".equals(paramMap.get("resultCode"))) {
            log.info("员投资异步回调投资失败：" + JSON.toJSONString(paramMap));
            return "fail";
        }

        String agentBillNo = (String) paramMap.get("agentBillNo");

        // 幂等性校验，根据投资订单号判断
        boolean hasSave = transFlowService.isSaveTransFlow(agentBillNo);
        Assert.isTrue(!hasSave, ResponseEnum.RECHARGE_CHONGFU);


        // 调用业务层方法
        lendItemService.notifyInvest(paramMap);

        return "success";
    }
}

